import { Injectable, LoggerService as NestLoggerService } from '@nestjs/common'
import { createLogger, Logger, format, transports } from 'winston'
import DailyRotateFile from 'winston-daily-rotate-file'
import { ConfigService } from '@nestjs/config'

@Injectable()
export class LoggerService implements NestLoggerService {
  private logger: Logger
  public maxSize: string = '20m' // 添加maxSize属性

  constructor(private configService: ConfigService) {
    this.logger = createLogger({
      level: this.configService.get('LOG_LEVEL', 'info'),
      format: format.combine(
        format.timestamp({
          format: 'YYYY-MM-DD HH:mm:ss'
        }),
        format.errors({ stack: true }),
        format.json()
      ),
      defaultMeta: { service: 'cms-api' },
      transports: [
        // 控制台输出
        new transports.Console({
          format: format.combine(format.colorize(), format.simple())
        }),
        // 错误日志文件
        new DailyRotateFile({
          filename: 'logs/error-%DATE%.log',
          datePattern: 'YYYY-MM-DD',
          level: 'error',
          maxSize: this.maxSize,
          maxFiles: '14d',
          format: format.combine(format.timestamp(), format.json())
        }),
        // 所有日志文件
        new DailyRotateFile({
          filename: 'logs/combined-%DATE%.log',
          datePattern: 'YYYY-MM-DD',
          maxSize: this.maxSize,
          maxFiles: '30d',
          format: format.combine(format.timestamp(), format.json())
        })
      ]
    })
  }

  log(message: string, context?: string) {
    this.logger.info(message, { context })
  }

  info(message: string, context?: any) {
    this.logger.info(message, context)
  }

  error(message: string, trace?: string, context?: string) {
    this.logger.error(message, { trace, context })
  }

  warn(message: string, context?: string) {
    this.logger.warn(message, { context })
  }

  debug(message: string, context?: any) {
    this.logger.debug(message, context)
  }

  verbose(message: string, context?: string) {
    this.logger.verbose(message, { context })
  }

  /**
   * 记录HTTP请求日志
   */
  logRequest(req: any, res: any, responseTime: number) {
    const { method, url, ip, headers } = req
    const { statusCode } = res

    this.logger.info('HTTP Request', {
      method,
      url,
      ip,
      userAgent: headers['user-agent'],
      statusCode,
      responseTime: `${responseTime}ms`
    })
  }

  /**
   * 记录数据库操作日志
   */
  logDatabase(operation: string, table: string, duration: number, error?: any) {
    if (error) {
      this.logger.error('Database Error', {
        operation,
        table,
        duration: `${duration}ms`,
        error: error.message,
        stack: error.stack
      })
    } else {
      this.logger.debug('Database Operation', {
        operation,
        table,
        duration: `${duration}ms`
      })
    }
  }

  /**
   * 记录用户操作日志
   */
  logUserAction(userId: string, action: string, resource?: string, details?: any) {
    this.logger.info('User Action', {
      userId,
      action,
      resource,
      details,
      timestamp: new Date().toISOString()
    })
  }

  /**
   * 记录安全事件日志
   */
  logSecurity(event: string, ip: string, userId?: string, details?: any) {
    this.logger.warn('Security Event', {
      event,
      ip,
      userId,
      details,
      timestamp: new Date().toISOString()
    })
  }

  /**
   * 记录性能日志
   */
  logPerformance(operation: string, duration: number, details?: any) {
    this.logger.info('Performance', {
      operation,
      duration: `${duration}ms`,
      details
    })
  }
}
